package com.ihomey.linkuphome.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.ihomey.cc.library.util.DensityUtil;
import com.ihomey.linkuphome.DeviceController;
import com.ihomey.linkuphome.R;
import com.ihomey.linkuphome.SpacesItemDecoration;
import com.ihomey.linkuphome.WrapContentLinearLayoutManager;
import com.ihomey.linkuphome.adapter.DeviceListAdapter;
import com.ihomey.linkuphome.base.BaseFragment;
import com.ihomey.linkuphome.entities.SingleDevice;
import com.ihomey.linkuphome.listeners.AssociationListener;
import com.ihomey.linkuphome.listeners.OnItemClickListener;
import com.ihomey.linkuphome.listeners.RemovedListener;
import com.ihomey.linkuphome.util.BindView;
import com.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/4/20.
 */

public class DeviceFragment extends BaseFragment implements OnItemClickListener, AssociationListener, RemovedListener {

    private static final int CHECKING_SCAN_INFO_TIME_MS = (5 * 1000);

    @BindView(id = R.id.rcv_devices)
    private SwipeMenuRecyclerView rcv_devices;
    private MaterialDialog mProgress = null;

    private MainActivity mainActivity;
    private Fragment mMainFragment;
    private DeviceController mController;
    private List<SingleDevice> deviceList = new ArrayList<SingleDevice>();
    private DeviceListAdapter deviceListAdapter;
    private boolean isShare = false;


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            onVisible();
        }
    }

    public static DeviceFragment newInstance(int lightType) {
        DeviceFragment fragment = new DeviceFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("lightType", lightType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.fragment_device, null);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mainActivity = (MainActivity) activity;
            mController = (DeviceController) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DeviceController callback interface.");
        }
    }

    protected void onVisible() {
        mMainFragment = this;
        initData();
        rcv_devices.setAdapter(deviceListAdapter);
        deviceListAdapter.setOnItemClickListener(this);
        if (!isShare) {
            rcv_devices.setSwipeMenuCreator(swipeMenuCreator);
            rcv_devices.setSwipeMenuItemClickListener(menuItemClickListener);
            mController.discoverDevices(true, this);
            startCheckingScanInfo();
        }
    }


    private void startCheckingScanInfo() {
        mController.postRunnable(checkScanInfoRunnable);
    }


    private Runnable checkScanInfoRunnable = new Runnable() {
        @Override
        public void run() {
            mainActivity.getMeshHandler().postDelayed(checkScanInfoRunnable, CHECKING_SCAN_INFO_TIME_MS);
        }
    };

    @Override
    public void initData() {
        super.initData();
        deviceList = mController.getDevices();
        deviceListAdapter = new DeviceListAdapter(deviceList);
        isShare = getActivity().getSharedPreferences("ihomey", Activity.MODE_PRIVATE).getBoolean("isShare" + mController.getDeviceType(), false);
    }

    @Override
    public void initWidget(View parentView) {
        super.initWidget(parentView);
        LinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(getActivity());
        rcv_devices.setLayoutManager(linearLayoutManager);
        rcv_devices.setItemAnimator(new DefaultItemAnimator());
        rcv_devices.addItemDecoration(new SpacesItemDecoration(DensityUtil.dip2px(getActivity(), 3)));
        deviceListAdapter.setOnItemClickListener(this);
    }


    @Override
    public void newUuid(UUID uuid, int uuidHash, int rssi, int ttl) {

    }

    @Override
    public void newAppearance(int uuidHash, byte[] appearance, String shortName) {
        boolean existing = false;
        for (SingleDevice info : deviceList) {
            if (info.getUuidHash() == uuidHash) {
                existing = true;
                break;
            }
        }
        if (!existing) {
            if (mController.getDeviceType() == 1 && !TextUtils.equals(shortName, "iHomey R2") && (TextUtils.equals(shortName, "iHomey C3") || shortName.startsWith("iHomey"))) {
                deviceList.add(0, new SingleDevice(0, uuidHash, mController.getDeviceType(), "Linkuphome C3"));
                deviceListAdapter.notifyItemInserted(0);
                deviceListAdapter.notifyItemRangeChanged(0, deviceList.size());
            } else if (mController.getDeviceType() == 2 && (TextUtils.equals(shortName, "iHomey R2"))) {
                deviceList.add(0, new SingleDevice(0, uuidHash, mController.getDeviceType(), "Linkuphome R2"));
                deviceListAdapter.notifyItemInserted(0);
                deviceListAdapter.notifyItemRangeChanged(0, deviceList.size());
            }
        }
    }

    @Override
    public void associationProgress(int progress, String message) {
        if (progress >= 0 && progress < 100) {
            mProgress.incrementProgress(progress - mProgress.getCurrentProgress());
        }
    }

    @Override
    public void deviceAssociated(int deviceId, boolean success, String message) {
        if (success) {
            hideDialog();
            SingleDevice device = (SingleDevice) mController.getDevice(deviceId);
            int position = deviceList.indexOf(device);
            deviceList.get(position).setDeviceId(deviceId);
            deviceListAdapter.notifyItemChanged(position);
        } else {
            hideDialog();
            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onItemClick(int position) {
        SingleDevice device = deviceList.get(position);
        if (device.getDeviceId() == 0) {
            showDialog(R.string.associating, true);
            mController.associateDevice(device.getUuidHash(), null);
        } else {
            LightFragment lightFragment = (LightFragment) getParentFragment();
            lightFragment.updateControls(device.getDeviceId());
        }
    }

    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.item_height);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity()).setBackgroundDrawable(R.drawable.selector_red)
                    .setText(R.string.delete).setTextSize(16).setTextColor(Color.WHITE).setWidth(width).setHeight(height);
            swipeRightMenu.addMenuItem(deleteItem);
        }
    };


    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。
            final SingleDevice device = deviceList.get(adapterPosition);
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                if (device.getDeviceId() != 0) {
                    new MaterialDialog.Builder(getActivity()).content(R.string.confirm_remove).canceledOnTouchOutside(false).negativeText(R.string.cancel).positiveText(R.string.confirm).onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            mController.removeDevice(device, (RemovedListener) mMainFragment);
                            showDialog(R.string.removing, false);
                        }
                    }).build().show();
                }
            }
        }
    };

    private void showDialog(int textRes, boolean hasProgress) {
        MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity()).canceledOnTouchOutside(false)
                .content(textRes).backgroundColorRes(R.color.white).contentColorRes(R.color.text_colorPrimaryDark).keyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                        return true;
                    }
                })
                .contentGravity(GravityEnum.CENTER);
        if (hasProgress) {
            builder.progress(false, 100, false);
        } else {
            builder.progress(true, 0).progressIndeterminateStyle(false);
        }
        mProgress = builder.build();
        mProgress.show();
    }

    private void hideDialog() {
        if (mProgress != null) {
            mProgress.dismiss();
            mProgress = null;
        }
    }

    @Override
    public void onDeviceRemoved(int deviceId, boolean success) {
        hideDialog();
        if (success) {
            SingleDevice device = new SingleDevice(deviceId, mController.getDeviceType(), null);
            int adapterPosition = deviceList.indexOf(device);
            if (adapterPosition != -1) {
                deviceList.remove(adapterPosition);
                deviceListAdapter.notifyItemRemoved(adapterPosition);
                deviceListAdapter.notifyItemRangeChanged(0, deviceList.size() - adapterPosition);
            }
        } else {
            mController.removeDeviceLocally(deviceId, (RemovedListener) mMainFragment);
        }
    }
}
